/*
 * TYU计科系 （C）版权所有 2022-3-22
 */
package cn.edu.tyu.finance.thingstype.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.tyu.finance.util.DbUtil;
import cn.edu.tyu.finance.util.StringUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


/**
 * 添加用户
 * @author Evelyn
 * @version 1.0
 * Servlet implementation class AddUserServlet
 */
@WebServlet("/AddUser")  //与jsp上的action名字必须完全一致
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * 处理网页发来的get请求
	 * @param request 请求对象 
	 * @param response 响应对象
	 */
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.点击添加后，接受网页传来的数据
		String uname=request.getParameter("username");		
		String upsw=request.getParameter("userpsw");
		String upswMD5=StringUtil.getMD5(upsw);
		//2.连接数据库，把接收到的数据写入表里
		Connection conn=null;
		PreparedStatement pstmt=null;//准备网页需要用到的数据
		conn=DbUtil.getConnection();
		String sql="INSERt INTO users VALUES(?,?,?)";
		int flag=0;
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1,(int)(Math.random()*1000)+"");//1-999之内的随机整数，然后转换成字符串类型
			pstmt.setString(2,uname);
			pstmt.setString(3,upswMD5);
		
			flag=pstmt.executeUpdate();   //执行数据库命令
			if(flag==0) {
				response.sendRedirect("fail.jsp");
			}
			else {
				response.sendRedirect("ok.jsp");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//3.关闭连接，数据库资源
			DbUtil.backConn(conn, pstmt, null);
		}
		
		
	}

	/**
	 * 处理网页发来的post请求
	 * @param request 请求对象 
	 * @param response 响应对象
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
